﻿@page "/"
@using Binance.Net.Interfaces
@using Blazor.DataProvider
@using CryptoExchange.Net.Objects.Sockets;
@using CryptoExchange.Net.Sockets

@inject BinanceDataProvider _dataProvider

<div>
    <h3>Live 24h change data</h3>
    @foreach (var tick in _ticks)
    {
        <div>@tick.Symbol | @tick.PriceChangePercent%</div>
    }
</div>

@code
{
    private IEnumerable<IBinanceTick> _ticks = new List<IBinanceTick>();
    private UpdateSubscription _subscription;

    protected override async Task OnInitializedAsync()
    {
        var callResult = await _dataProvider.Get24HPrices();
        if (callResult)
            _ticks = callResult.Data;

        var subResult = await _dataProvider.SubscribeTickerUpdates(HandleTickUpdates);
        if (subResult)
            _subscription = subResult.Data;
    }

    private void HandleTickUpdates(DataEvent<IEnumerable<IBinanceTick>> update)
    {
        foreach (var tick in update.Data)
        {
            var symbol = _ticks.SingleOrDefault(t => t.Symbol == tick.Symbol);
            if (symbol != null)
                symbol.PriceChangePercent = tick.PriceChangePercent;
        }

        InvokeAsync(StateHasChanged);
    }
}